#include "../include/server.h"

int serverCd(int sockFd, int *curDirID, int ownerID, char *dirName){
    //先判断目录名是否合法
    //合法就发送cd之后的目录名给客户端，并修改当前路径ID
    //不合法就通知客户端
    int bufID = query_cd(dirName, *curDirID, ownerID);
    char flag[2] = {0};
    char curPath[128] = {0};
    int parentID = -1;


    if(!strcmp(dirName, "..")){
        //返回上一级目录
        /* puts(dirName); */
        /* printf("curDirID = %d\n", *curDirID); */
        // cd ..   切换到上一级目录
        if(*curDirID == 0){
            //在根目录，非法指令
            bufID = -1;
            flag[0] = 'u';
            send(sockFd, flag, 1, 0);
            printf("illegal path!\n");
        }
        else{
            parentID = query_parentID(*curDirID, ownerID);
            getPath(curPath, parentID, ownerID);
            *curDirID = parentID;
            /* printf("curPath = %s\n", curPath); */
            flag[0] = 'a';
            send(sockFd, flag, 1, 0);
            send(sockFd, curPath, strlen(curPath)+1, 0);
            //更新user表的pwd
            updatePwd(ownerID, curPath);
        }
        return 1;
    }

    if(bufID == -1){
        //非法路径
        flag[0] = 'u';
        send(sockFd, flag, 1, 0);
        printf("illegal path!\n");
    }
    else{
        printf("curDir = %s\n", dirName);
        *curDirID = bufID;    //修改当前工作目录
        /* printf("id = %d\n", *curDirID); */
        getPath(curPath, bufID, ownerID);
        /* printf("curPath = %s\n", curPath); */
        flag[0] = 'a';
        send(sockFd, flag, 1, 0);
        send(sockFd, curPath, strlen(curPath)+1, 0);
        //更新user表的pwd
        updatePwd(ownerID, curPath);
    }

    return 1;
}
